package org.finesys.samples.file.aio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AioServer {

    public static void main(String[] args) {

        try {
            //创建一个异步服务器套接字通道
            AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            //绑定端口
            asynchronousServerSocketChannel.bind(new InetSocketAddress(9090));
            System.out.println("服务端启动完成，等待客户端连接");
            //开始接收新的客户端连接
            asynchronousServerSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                @Override
                public void completed(AsynchronousSocketChannel clientChannel, Object attachment) {
                    //当一个新的客户端连接完成，再次接收新的客户端连接
                    asynchronousServerSocketChannel.accept(null, this);
                    //创建一个新的缓冲区来读取数据
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    try {
                        //获取客户端地址
                        InetSocketAddress inetSocketAddress = (InetSocketAddress) clientChannel.getRemoteAddress();
                        InetAddress inetAddress = inetSocketAddress.getAddress();
                        int port = inetSocketAddress.getPort();
                        String clientInfo = "客户端：" + inetAddress + "端口:" + port + "，连接成功！";
                        System.out.println(clientInfo);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //从异步套接字中读取数据
                    clientChannel.read(byteBuffer, byteBuffer, new ReadCompletionHandler(clientChannel));
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("连接失败");
                }
            });
            //保持客户端开启
            Thread.sleep(Integer.MAX_VALUE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }

    }
}
